<template>
  <div class="user-center-container">
    <el-card class="user-card">
      <h2 class="title">个人设置</h2>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="base">
          <div class="avatar-section">
            <div class="avatar-label">头像</div>
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.avatar" :src="form.avatar" class="avatar" />
              <el-icon v-else class="avatar-icon"><Plus /></el-icon>
              <div class="avatar-tip">点击上传头像</div>
            </el-upload>
            <div class="avatar-desc">支持JPG、PNG格式,不超过2MB</div>
            <el-button 
              v-if="form.avatar && form.avatar !== originalAvatar" 
              type="primary" 
              size="small" 
              @click="saveAvatar"
              :loading="avatarLoading"
              style="margin-top: 10px;"
            >
              保存头像
            </el-button>
          </div>
          <el-form :model="form" :rules="rules" ref="formRef" label-width="80px" class="info-form">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="form.userId" disabled />
            </el-form-item>
            <el-form-item label="用户名" prop="username" required>
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email" required>
              <el-input v-model="form.email" placeholder="请输入邮箱" />
              <div class="input-desc">请输入有效的邮箱地址（例如：example@domain.com）</div>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入电话" />
              <div class="input-desc">请输入11位有效的手机号（例如：13800138000）</div>
            </el-form-item>
            <el-form-item label="角色" prop="roles">
              <el-tag v-for="role in form.roles" :key="role" type="primary" class="role-tag">
                {{ role }}
              </el-tag>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-tag :type="form.status === 'active' ? 'success' : 'danger'">
                {{ form.status === 'active' ? '正常' : '禁用' }}
              </el-tag>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit" :loading="loading">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="密码修改" name="password">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="80px" class="info-form">
            <el-form-item label="原密码" prop="oldPassword" required>
              <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword" required>
              <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
              <div class="input-desc">密码长度需在6-20个字符之间</div>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword" required>
              <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
              <div class="input-desc">请再次输入相同的新密码</div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onPasswordSubmit" :loading="passwordLoading">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useAdminStore } from '@/stores/admin'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'

const adminStore = useAdminStore()
const activeTab = ref('base')
const formRef = ref()
const passwordFormRef = ref()
const loading = ref(false)
const passwordLoading = ref(false)
const avatarLoading = ref(false)
const originalAvatar = ref('')

const form = reactive({
  userId: '',
  avatar: '',
  username: '',
  email: '',
  phone: '',
  roles: [],
  status: 'active'
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的新密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 从store获取用户信息
onMounted(() => {
  let userInfo = adminStore.user
  if (!userInfo) {
    const storedUserInfo = localStorage.getItem('adminUserInfo')
    if (storedUserInfo) {
      userInfo = JSON.parse(storedUserInfo)
      adminStore.setUser(userInfo)
    }
  }
  
  if (userInfo) {
    form.userId = userInfo.id || ''
    form.username = userInfo.userName || ''
    form.email = userInfo.email || ''
    form.phone = userInfo.phoneNumber || ''
    form.avatar = userInfo.avatarUrl || ''
    originalAvatar.value = userInfo.avatarUrl || ''
    form.roles = userInfo.roles || userInfo.roleTypes || []
    form.status = userInfo.status || 'active'
  }
})

function handleAvatarChange(file) {
  if (file && file.raw) {
    form.avatar = URL.createObjectURL(file.raw)
  }
}

function beforeAvatarUpload(file) {
  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPGorPNG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

async function saveAvatar() {
  if (!form.avatar || form.avatar === originalAvatar.value) {
    ElMessage.warning('请先选择新的头像')
    return
  }
  
  avatarLoading.value = true
  try {
    // 这里可以调用后端API上传头像
    // 暂时先保存到本地
    ElMessage.success('头像保存成功')
    originalAvatar.value = form.avatar
    
    // 更新store和localStorage
    adminStore.updateUserInfo({
      avatarUrl: form.avatar
    })
    
    const updatedUserInfo = { ...adminStore.user, avatarUrl: form.avatar }
    localStorage.setItem('adminUserInfo', JSON.stringify(updatedUserInfo))
    
  } catch (error) {
    console.error('保存头像失败:', error)
    ElMessage.error('头像保存失败，请重试')
  } finally {
    avatarLoading.value = false
  }
}

async function onSubmit() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 调用后端API更新用户信息
        await userApi.updateUserInfo(form.userId, {
          userName: form.username,
          email: form.email,
          phoneNumber: form.phone,
          avatarUrl: form.avatar
        })
        
        // 更新store和localStorage
        adminStore.updateUserInfo({
          userName: form.username,
          email: form.email,
          phoneNumber: form.phone,
          avatarUrl: form.avatar
        })
        
        const updatedUserInfo = { ...adminStore.user, ...form }
        localStorage.setItem('adminUserInfo', JSON.stringify(updatedUserInfo))
        
        ElMessage.success('保存成功')
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('保存失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

async function onPasswordSubmit() {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        // 调用后端API修改密码
        await userApi.changePassword(form.userId, {
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        
        ElMessage.success('密码修改成功')
        // 清空表单
        passwordForm.oldPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('密码修改失败，请重试')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}
</script>

<style scoped>
.user-center-container {
  min-height: 100vh;
  padding: 40px 0;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.95) 0%, rgba(22, 33, 62, 0.95) 100%);
}
.user-card {
  width: 600px;
  margin: 0 auto;
  border-radius: 16px;
  background: linear-gradient(135deg, rgba(26, 26, 46, 0.98) 0%, rgba(22, 33, 62, 0.98) 100%);
  box-shadow: 0 4px 20px rgba(0, 212, 255, 0.12);
  border: 1px solid rgba(0, 212, 255, 0.18);
  color: #fff;
}
.title {
  font-size: 26px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #fff;
}
.avatar-section {
  text-align: center;
  margin-bottom: 30px;
}
.avatar-label {
  font-size: 16px;
  margin-bottom: 10px;
  color: #b3e5fc;
}
.avatar-uploader {
  display: inline-block;
  position: relative;
  width: 120px;
  height: 120px;
  border: 1px dashed #00d4ff;
  border-radius: 50%;
  cursor: pointer;
  margin-bottom: 8px;
  background: rgba(0, 212, 255, 0.08);
}
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #00d4ff;
}
.avatar-icon {
  font-size: 40px;
  color: #00d4ff;
  margin-top: 40px;
}
.avatar-tip {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 10px;
  text-align: center;
  color: #b3e5fc;
  font-size: 14px;
}
.avatar-desc {
  color: #b3e5fc;
  font-size: 14px;
  margin-bottom: 10px;
}
.info-form {
  margin-top: 10px;
  background: rgba(0, 212, 255, 0.04);
  border-radius: 12px;
  padding: 24px 18px 10px 18px;
  box-shadow: 0 2px 8px rgba(0, 212, 255, 0.08);
}
.el-form-item__label, .el-form-item__content, .el-input__inner, .el-tag, .el-button {
  color: #fff !important;
}
.el-input__inner {
  background: rgba(26, 26, 46, 0.7) !important;
  border: 1px solid rgba(0, 212, 255, 0.18) !important;
  color: #fff !important;
}
.el-input__inner:focus {
  border-color: #00d4ff !important;
}
.el-card {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}
.input-desc {
  color: #b3e5fc;
  font-size: 12px;
  margin-top: 2px;
}
.role-tag {
  margin-right: 8px;
  margin-bottom: 4px;
  background: rgba(0, 212, 255, 0.18) !important;
  border: 1px solid #00d4ff !important;
  color: #fff !important;
}
.el-tag--success {
  background: rgba(0, 255, 128, 0.18) !important;
  border: 1px solid #00ff80 !important;
  color: #fff !important;
}
.el-tag--danger {
  background: rgba(255, 0, 64, 0.18) !important;
  border: 1px solid #ff4060 !important;
  color: #fff !important;
}
.el-tabs__item {
  color: #b3e5fc !important;
}
.el-tabs__item.is-active {
  color: #00d4ff !important;
}
.el-tabs__nav {
  border-bottom: 1px solid #00d4ff !important;
}
.el-button--primary {
  background: linear-gradient(135deg, #00d4ff 0%, #0099cc 100%) !important;
  border: none !important;
  color: #fff !important;
  font-weight: 600;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 212, 255, 0.18) !important;
  transition: all 0.3s;
}
.el-button--primary:hover {
  background: linear-gradient(135deg, #0099cc 0%, #0077a3 100%) !important;
}
</style> 